package knu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Ray on 2014-12-10.
 */
@WebServlet(name = "Append_Servlet")
public class Append_Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String pn = request.getParameter("pn");
        Cookie[] cookies = request.getCookies();
        //response.getWriter().println("asd");
        String uri = request.getRequestURI();
        // response.getWriter().println(request.getRequestURI());
        String oldpn=new String();
        if(cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("pnlist")) {
                    pn = cookie.getValue() + " " + pn;

                }
            }
        }//
        if (uri.equals("/AppendPro"))
        {
            response.addCookie(new Cookie("pnlist",pn));
            //response.getWriter().println("장바구니 품목이 저장되었습니다 <a href=\"/shoping.jsp\">다시방문하기</a>");

        }
        else if (uri.equals("/DeletePro"))
        {
            String del=request.getParameter("pn");
            int delnum=Integer.parseInt(del);
            if(delnum == -1)
            {

                Cookie cookie =new Cookie("pnlist",null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }


            else {
                //pn = pn.substring(delnum * 2, delnum * 2 + 1);
                String temp=new String();
                temp=pn.substring(0,delnum*2);
                temp+=pn.substring(delnum*2+2,pn.length()-1);
                pn=temp;
                if(pn.length()==1)
                    pn="";
                response.addCookie(new Cookie("pnlist", pn));

            }

            //response.getWriter().println("장바구니 품목이 삭제되었습니다. <a href=\"/shoping.jsp\">장바구니 보러가기</a>");
        }
        response.sendRedirect("/shoping.jsp");


    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
